package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.system.domain.BabyUser;
import com.ruoyi.system.mapper.BabyUserMapper;
import com.ruoyi.web.utils.AesCbcUtil;
import com.ruoyi.web.utils.FileNameUtil;
import com.ruoyi.web.utils.HttpResponse;
import com.ruoyi.web.utils.WeChatAuth;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IBabyUserService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 * 
 * @author ruoyi
 * @date 2021-11-26
 */
@RestController
@RequestMapping("/api/user")
public class BabyUserController extends BaseController
{
    @Autowired
    private IBabyUserService babyUserService;

    /**
     * 查询【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(BabyUser babyUser)
    {
        startPage();
        List<BabyUser> list = babyUserService.selectBabyUserList(babyUser);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BabyUser babyUser)
    {
        List<BabyUser> list = babyUserService.selectBabyUserList(babyUser);
        ExcelUtil<BabyUser> util = new ExcelUtil<BabyUser>(BabyUser.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") String userId)
    {
        return AjaxResult.success(babyUserService.selectBabyUserByUserId(userId));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BabyUser babyUser)
    {
        return toAjax(babyUserService.insertBabyUser(babyUser));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BabyUser babyUser)
    {
        return toAjax(babyUserService.updateBabyUser(babyUser));
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "【请填写功能名称】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable String[] userIds)
    {
        return toAjax(babyUserService.deleteBabyUserByUserIds(userIds));
    }

    @ApiOperation("获取用户信息byUserID")
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public HttpResponse getUserInfoRequest(@RequestParam String userId) {
        BabyUser babyUser = babyUserService.selectBabyUserByUserId(userId);
        return HttpResponse.ok().setData(babyUser);
    }

    @ApiOperation("微信小程序静默授权")
    @RequestMapping(value = "/silenceLogin", method = RequestMethod.POST)
    public HttpResponse wechatAuthLogin(@RequestParam String code) {
        Map<String, String> map = WeChatAuth.authWeChatAction(code);
        BabyUser babyUser = babyUserService.selectBabyUserByOpenId(map.get("openId"));
        if (babyUser != null) {
            Map oleMap = JSON.parseObject(JSON.toJSONString(babyUser));
            oleMap.put("isNew", 0);
            return HttpResponse.ok().setData(oleMap);
        } else {
            Map newMap = new HashMap();
            newMap.put("openId", map.get("openId"));
            newMap.put("isNew", "1");
            return HttpResponse.ok().setData(newMap);
        }
    }

    @ApiOperation("微信授权获取用户信息")
    @RequestMapping(value = "/authUserInfo", method = RequestMethod.POST)
    public HttpResponse authUserInfoRequest(@RequestParam String code, String encryptedData, String iv) {

        Map<String, String> map = WeChatAuth.authWeChatAction(code);
        JSONObject jsons = null;
        try{
            //拿到用户session_key和用户敏感数据进行解密，拿到用户信息。
            String decrypts= AesCbcUtil.decrypt(encryptedData,map.get("session_key"),iv,"utf-8");//解密
            jsons = JSONObject.parseObject(decrypts);
        }catch (Exception e) {
            e.printStackTrace();
        }

        if (jsons != null) {
            BabyUser babyUser = babyUserService.selectBabyUserByOpenId(map.get("openId"));
            if (babyUser != null) {
                Map oldMap = JSON.parseObject(JSON.toJSONString(babyUser));
                oldMap.put("isNew", 0);
                return HttpResponse.ok().setData(oldMap);
            }else {
                BabyUser newUser = new BabyUser();
                newUser.setUserId(FileNameUtil.getUUID());
                newUser.setRelevanceId("");
                newUser.setOpenId(map.get("openId"));
                newUser.setUserName(jsons.getString("nickName"));
                newUser.setUserImg(jsons.getString("avatarUrl"));
                newUser.setGender(jsons.getInteger("gender").longValue());
                newUser.setPhone("");
                newUser.setStatus(0l);
                newUser.setIntoTime(FileNameUtil.formatDate(new Date()));
                int insert = babyUserService.insertBabyUser(newUser);
                if (insert==1) {
                    Map oldMap = JSON.parseObject(JSON.toJSONString(newUser));
                    oldMap.put("isNew", 0);
                    return HttpResponse.ok().setData(oldMap);
                }else {
                    return HttpResponse.error("用户注册失败");
                }
            }
        }
        else {
            return HttpResponse.error("授权失败");
        }
    }
}
